package com.example.hosinject.inject;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InjectUtils {
    public static void inject(AbilitySlice abilitySlice) {
        bindView(abilitySlice);//绑定视图控件
        bindMethod(abilitySlice);//绑定方法
    }


    private static void bindView(AbilitySlice abilitySlice) {
        Class<? extends AbilitySlice> aClass = abilitySlice.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field f : declaredFields) {
            SliceInjectView annotation = f.getAnnotation(SliceInjectView.class);
            if (annotation != null)//判断一下是否存在MyInjectView注解
            {
                int resID = annotation.value();
                final Component view = abilitySlice.findComponentById(resID);
                f.setAccessible(true);
                try {
                    f.set(abilitySlice, view);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void bindMethod(final AbilitySlice abilitySlice) {
        final Class<? extends AbilitySlice
                > aClass = abilitySlice.getClass();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (final Method m : declaredMethods) {
            SliceInjectViewClick annotation = m.getAnnotation(SliceInjectViewClick.class);
            if (annotation != null)//判断一下是否存在MyInjectView注解
            {
                int[] resID = annotation.value();
                for (int id : resID) {
                    final Component view = abilitySlice.findComponentById(id);
                    if (view == null) {
                        return;
                    }
                    view.setClickedListener(component -> {
                        m.setAccessible(true);
                        try {
                            m.invoke(abilitySlice, view);//当view点击时执行绑定的方法
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        }
    }
}
